package com.zhanghe.wzq.handler;

import com.zhanghe.protocol.serializer.SerializerManager;
import com.zhanghe.protocol.v1.Packet;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * CommandEncoder
 *
 * @author Clevo
 * @date 2018/12/23
 */
public class CommandEncoder extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if(msg instanceof Packet){
            byte[] bytes = SerializerManager.getDefault().serialize(msg);
            System.out.println(msg);
            TextWebSocketFrame tws = new TextWebSocketFrame(new String(bytes));
            ctx.channel().writeAndFlush(tws);
        }else{
            super.write(ctx, msg, promise);
        }
    }
}
